package com.pureman.androidapp.socket;

import com.pureman.androidapp.utils.LogUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * Created by Administrator on 2016/6/24 0024.
 * <p/>
 * TCP/IP协议连接
 */
public class TCPUtil extends Thread {

    private Socket socket;
    private OutputStream outputStream;
//    private InputStream inputStream;

    public void setReconnect(boolean reconnect) {
        this.reconnect = reconnect;
    }

    private boolean reconnect = false;

    public static TCPUtil getInstance() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static TCPUtil instance = new TCPUtil();
    }

    public TCPUtil() {
        start();
    }

    @Override
    public void run() {
        while (true) {
            while (this.reconnect) {
                LogUtils.i("TCPUtil-->run");
                try {
                    socket = new Socket();
                    socket.connect(new InetSocketAddress(ConnectConfig.HOST, ConnectConfig.PORT), ConnectConfig.TIME_OUT);
                    socket.setKeepAlive(true);
                    if (!socket.getTcpNoDelay()) {
                        socket.setTcpNoDelay(true);
                    }

                    LogUtils.i("tcp scoket......");

                    outputStream = socket.getOutputStream();
//                    inputStream = socket.getInputStream();

                    this.reconnect = false;

//                    send(ConnectConfig.WIFI_SEND_INIT);
                } catch (UnknownHostException e) {//主机名字或IP错误
                    e.printStackTrace();
                    this.reconnect = true;
                    LogUtils.i("UnknownHostException-->" + e.getMessage());
                } catch (ConnectException e) {//服务器拒绝连接、服务器没有启动、（超出队列数，拒绝连接）
                    e.printStackTrace();
                    this.reconnect = true;
                    LogUtils.i("ConnectException-->" + e.getMessage());
                } catch (BindException e) {//Socket对象无法与制定的本地IP地址或端口绑定
                    e.printStackTrace();
                    this.reconnect = true;
                    LogUtils.i("BindException-->" + e.getMessage());
                } catch (SocketTimeoutException e) {// 连接超时
                    e.printStackTrace();
                    this.reconnect = true;
                    LogUtils.i("SocketTimeoutException-->" + e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    this.reconnect = true;
                    LogUtils.i("IOException-->" + e.getMessage());
                }
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean connectionStatus() {
        if (socket != null) {
            LogUtils.i("TCPUtil-->" + socket.isConnected());
            LogUtils.i("TCPUtil-->" + socket.isClosed());
        }
        return socket == null ? false : (socket.isConnected() && !socket.isClosed());
    }

    public void send(final byte[] bytes) {
        LogUtils.i("tcp send-len->" + bytes.length);
        LogUtils.i("tcp bytes string-->" + "[" + byte2hex(bytes) + "]");

//                int len = bytes.length;
//        for (int i = 0; i < len; i++) {
//            LogUtils.i("MainActivity bytes 2-->" + bytes[i]);
//        }

//        try {
//            LogUtils.i("tcp send-content->" + new String(bytes, "ISO-8859-1"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }


        try {
            try {
                Thread.sleep(ConnectConfig.SLEEP);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            outputStream.write(bytes);
            outputStream.flush();

//                    byte[] buff = new byte[128];
//                    String str;
//                    while ((inputStream.read(buff)) != -1) {
//                        str = new String(buff, "ISO-8859-1");
//                        LogUtils.i("tcp receive-->" + str);
//                    }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        if (connectionStatus()) {
            try {
                outputStream.close();
//                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String byte2hex(byte[] buffer) {
        String h = "";
        for (int i = 0; i < buffer.length; i++) {
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            if (i == 0) {
                h = h + temp;
            } else {
                h = h + " " + temp;
            }
        }
        return h;
    }
}
